package com.icss.train_sys_back.controller.admin.system_manage;

import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.icss.train_sys_back.entity.ResponseResult;
import com.icss.train_sys_back.entity.ResultEnum;
import com.icss.train_sys_back.entity.system_manage.UserEntity;
import com.icss.train_sys_back.service.system_service.UserService;
import jakarta.servlet.ServletOutputStream;
import lombok.extern.slf4j.Slf4j;
import org.apache.ibatis.annotations.Delete;
import org.apache.poi.hssf.usermodel.*;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import jakarta.servlet.http.HttpServletResponse;

import java.io.IOException;
import java.io.OutputStream;
import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;

import java.util.List;
import java.util.Objects;

/**
 * @author wk
 * @desc
 * @date 2025/9/29 10:35
 */
@RestController
@RequestMapping("/admin/user_manage")
@Slf4j
public class UserManageController {
    @Autowired
    private UserService userService;

    //根据查询条件获取所有用户信息
    @GetMapping("/getList")
    public ResponseResult getAllUser(
            @RequestParam(defaultValue = "1") Integer page,
            @RequestParam(defaultValue = "8") Integer pageSize,
            @RequestParam(required = false) String username,//用户名
            @RequestParam(required = false) String name,//用户姓名，对应数据库表中的name
            @RequestParam(required = false) Integer roleId,
            @RequestParam(required = false) Integer status
    ) {
        log.info("获取所有用户+条件查询方法入参，page={},pageSize={},username={},name={},roleId={},status={}",
                page, pageSize, username, name, roleId, status);
        PageHelper.startPage(page, pageSize);
        List<UserEntity> userList = userService.getAllUser(username, name, roleId, status);
        log.info("结果：{}", userList);
        PageInfo<UserEntity> pageInfo = new PageInfo<>(userList);
        return ResponseResult.success(pageInfo);
    }

    //添加用户
    @PostMapping("/add")
    public ResponseResult addUser(@RequestBody UserEntity user) {
        log.info("添加用户功能入参：{}", user);
        boolean res = userService.addUser(user);
        return res ? ResponseResult.success() : ResponseResult.fail(ResultEnum.FAIL);
    }

    //修改用户信息
    @PostMapping("/update")
    public ResponseResult updateUser(@RequestBody UserEntity user) {
        log.info("修改用户信息功能入参：{}", user);
        boolean res = userService.updateUser(user);
        return res ? ResponseResult.success() : ResponseResult.fail(ResultEnum.FAIL);
    }

    //删除指定用户
    @DeleteMapping("/delete/{userId}")
    public ResponseResult deleteUser(@PathVariable("userId") Integer userId) {
        log.info("删除ID为{}的用户", userId);
        boolean res = userService.deleteUser(userId);
        return res ? ResponseResult.success() : ResponseResult.fail(ResultEnum.FAIL);
    }

    //修改用户状态
    @GetMapping("/changeStatus")
    public ResponseResult changeStatus(
            @RequestParam(required = false) Integer newUserId,
            @RequestParam(required = false) Integer myStatus
    ) {
        log.info("修改某位用户的账号状态,userId={},status={}", newUserId, myStatus);
        boolean res = userService.changeStatus(newUserId, myStatus);
        return res ? ResponseResult.success() : ResponseResult.fail(ResultEnum.FAIL);
    }

    //检查用户是否登录
    @GetMapping("/checkLogin")
    public ResponseResult checkLogin(@RequestParam String userId) {
        if (Objects.equals(userId, "") || userId == null) {
            return ResponseResult.fail(ResultEnum.FAIL);
        }
        Integer myUserId = Integer.valueOf(userId);
        log.info("检查用户是否登录方法入参userId={}", userId);
        UserEntity user = userService.checkLogin(myUserId);
        log.info("查询结果：{}", user);
        return ResponseResult.success(user);
    }

    //导出用户列表excel
    @PostMapping("/export")
    public void export(HttpServletResponse response) {
        log.info("导出用户列表excel");
        try {
            // 1. 获取所有用户数据
            List<UserEntity> userList = userService.getAllUser(null, null, null, null);
            log.info("获取到的用户数据数量: {}", userList.size());

            // 2. 创建Excel工作簿和工作表
            HSSFWorkbook workbook = new HSSFWorkbook();
            HSSFSheet sheet = workbook.createSheet("用户列表");

            // 3. 创建表头行
            HSSFRow headerRow = sheet.createRow(0);
            String[] headers = {"用户ID", "用户名", "真实姓名", "性别", "出生日期", "手机号码", "邮箱", "状态", "角色", "创建时间"};

            for (int i = 0; i < headers.length; i++) {
                HSSFCell cell = headerRow.createCell(i);
                cell.setCellValue(headers[i]);
                // 设置表头样式
                HSSFCellStyle style = workbook.createCellStyle();
                HSSFFont font = workbook.createFont();
                font.setBold(true);
                style.setFont(font);
                cell.setCellStyle(style);
            }

            // 4. 填充用户数据
            for (int i = 0; i < userList.size(); i++) {
                UserEntity user = userList.get(i);
                HSSFRow row = sheet.createRow(i + 1);

                row.createCell(0).setCellValue(user.getUserId() != null ? user.getUserId() : 0);
                row.createCell(1).setCellValue(user.getUsername() != null ? user.getUsername() : "");
                row.createCell(2).setCellValue(user.getName() != null ? user.getName() : "");
                row.createCell(3).setCellValue(user.getSex() != null ? (user.getSex() == 1 ? "男" : "女") : "");
                row.createCell(4).setCellValue(user.getBirthday() != null ? new SimpleDateFormat("yyyy-MM-dd").format(user.getBirthday()) : "");
                row.createCell(5).setCellValue(user.getPhone() != null ? user.getPhone() : "");
                row.createCell(6).setCellValue(user.getEmail() != null ? user.getEmail() : "");
                row.createCell(7).setCellValue(user.getStatus() != null ? (user.getStatus() == 0 ? "正常" : "禁用") : "");
                row.createCell(8).setCellValue(user.getRole() != null && user.getRole().getRoleName() != null ? user.getRole().getRoleName() : "");
                row.createCell(9).setCellValue(user.getCreateTime() != null ? new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(user.getCreateTime()) : "");
            }

            // 5. 设置响应头，准备下载
            String fileName = "用户列表_" + new SimpleDateFormat("yyyyMMdd_HHmmss").format(new Date()) + ".xls";
            response.setContentType("application/vnd.ms-excel");
            response.setHeader("Content-Disposition", "attachment; filename=" + URLEncoder.encode(fileName, "UTF-8"));

            // 6. 输出Excel文件
            ServletOutputStream outputStream = response.getOutputStream();
            workbook.write(outputStream);
            outputStream.flush();
            outputStream.close();
            workbook.close();

            log.info("用户列表Excel导出成功");
        } catch (Exception e) {
            log.error("导出用户列表excel失败", e);
            // 如果发生异常，可以设置响应状态码
            response.setStatus(HttpServletResponse.SC_INTERNAL_SERVER_ERROR);
        }
    }
}
